package com.tyrone.gateway.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpServerExpectContinueHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyServer implements Runnable {
    @Override
    public void run() {
        NioEventLoopGroup boss = new NioEventLoopGroup(NettyServerConfig.BOSS_GROUP_THREADS);
        NioEventLoopGroup worker = new NioEventLoopGroup(NettyServerConfig.WORKER_GROUP_THREADS);
        try {
            Channel channel = new ServerBootstrap().group(boss, worker)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new HttpServerCodec());
                            ch.pipeline().addLast( new HttpObjectAggregator(512 * 1024));
                            ch.pipeline().addLast(new HttpContentCompressor());
                            ch.pipeline().addLast(new HttpServerExpectContinueHandler());
                            ch.pipeline().addLast(new ServerHandler());
                        }
                    }).bind(NettyServerConfig.PORT).addListener((ChannelFutureListener) future -> {
                        if (future.isSuccess()) log.info("netty server start up successfully");
                    }).sync().channel();

            channel.closeFuture().sync();
        } catch (Exception e) {
            log.error("netty server error : ", e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        Thread server = new Thread(new NettyServer());
        server.start();
    }


}
